package com.lzt.yijian.api;

import android.content.Context;

import com.lzt.yijian.api.inter.ApiService;
import com.lzt.yijian.util.AppUtil;
import com.lzt.yijian.util.LztLog;
import com.lzt.yijian.util.NetUtil;

import java.io.File;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

import io.reactivex.Observable;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;
import okhttp3.Cache;
import okhttp3.CacheControl;
import okhttp3.Interceptor;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.internal.cache.CacheInterceptor;
import okio.Buffer;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;

/**
 * 整个网络通信服务的启动控制，必须先调用初始化函数才能正常使用网络通信接口
 */
public class Api {
    //设缓存有效期为1天
    static final long CACHE_STALE_SEC = 60 * 60 * 24 * 1;
    //查询缓存的Cache-Control设置，为if-only-cache时只查询缓存而不会请求服务器，max-stale可以配合设置缓存失效时间
    private static final String CACHE_CONTROL_CACHE = "only-if-cached, max-stale=" + CACHE_STALE_SEC;

    //    static String HOST = "http://wthrcdn.etouch.cn/";
    static String HOST = "https://api.douban.com/v2/movie/";
    public ApiService apiService;
    private Retrofit mRetrofit;
    private OkHttpClient mOkHttpClient;
    private Context mContext;

    /**
     * 初始化网络通信服务
     */
    public void init(Context context) {
        mContext = context;
        initOkHttpClient(context);
        initRetrofit();
        if (apiService == null) {
            apiService = mRetrofit.create(ApiService.class);
        }
    }

    private void initOkHttpClient(Context context) {
        // 指定缓存路径,缓存大小80Mb
        Cache cache = new Cache(new File(AppUtil.getCacheDir(context), "HttpCache"),
                1024 * 1024 * 80);
        mOkHttpClient = new OkHttpClient.Builder()
                .cache(cache)
                .retryOnConnectionFailure(true)
                .addInterceptor(sLoggingInterceptor)
                .addInterceptor(sRewriteResponseInterceptor)
                .addNetworkInterceptor(sRewriteResponseInterceptor)
                .connectTimeout(10, TimeUnit.SECONDS)
                .build();
    }

    private void initRetrofit() {
        mRetrofit = new Retrofit.Builder()
                .client(mOkHttpClient)
                .baseUrl(HOST)
                .addConverterFactory(GsonConverterFactory.create())
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .build();
    }

    /**
     * 打印返回的json数据拦截器
     */
    private Interceptor sLoggingInterceptor = new Interceptor() {
        @Override
        public Response intercept(Chain chain) throws IOException {
            final Request request = chain.request();
            Buffer requestBuffer = new Buffer();
            if (request.body() != null) {
                request.body().writeTo(requestBuffer);
            } else {
                LztLog.d("LogTAG", "request.body() == null");
            }
            //打印url信息
            final Response response = chain.proceed(request);
            return response;
        }
    };

    private final Interceptor sRewriteResponseInterceptor = new Interceptor() {
        @Override
        public okhttp3.Response intercept(Chain chain) throws IOException {
            Request request = chain.request();
            if (!NetUtil.isNetworkAvailable(mContext)) {
                request = request.newBuilder().cacheControl(CacheControl.FORCE_CACHE).build();
                LztLog.e("LogTAG", "no network");
            }
            Response originalResponse = chain.proceed(request);
            if (NetUtil.isNetworkAvailable(mContext)) {
                //有网的时候读接口上的@Headers里的配置，你可以在这里进行统一的设置
                String cacheControl = request.cacheControl().toString();
                return originalResponse.newBuilder()
                        .header("Cache-Control", cacheControl)
                        .removeHeader("Pragma")
                        .build();
            } else {
                return originalResponse.newBuilder()
                        .header("Cache-Control", "public, " + CACHE_CONTROL_CACHE)
                        .removeHeader("Pragma")
                        .build();
            }
        }
    };

    public <T> void toSubscribe(Observable<T> o, Observer<T> s) {
        o.subscribeOn(Schedulers.io())
                .unsubscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(s);
    }

//    /**
//     * 用来统一处理Http的resultCode,并将HttpResult的Data部分剥离出来返回给subscriber
//     *
//     * @param <T> Subscriber真正需要的数据类型，也就是Data部分的数据类型
//     */
//    public class HttpResultFunc<T> implements Function<HttpResult<T>, T> {
//
//        @Override
//        public T apply(HttpResult<T> httpResult) {
//            if (!httpResult.isSuccess()) {
//                throw new APIException(httpResult.flag, httpResult.msg);
//            }
//            if(httpResult.isTokenExpired()) {
//                //Accesstoken过期
//                AppUtil.setCatheAccessToken(mContext, "");
//                WeexManager.getInstance().doLogin(mContext, false);
//            }
//            return httpResult.result;
//        }
//    }


}
